# -*- coding: utf-8 -*-
# Description: 读iot数据
# Created: zxj 2023/12/8
import time

import pandas as pd
import requests


class GetIotData:
    # 常量
    API_URL_TIME_BEFORE = "http://eplat.baogang.info/service/D_A_IOTDB_READ_DATA_0007"  # 向前获取时间戳
    API_URL_TIME_AFTER = "http://eplat.baogang.info/service/D_A_IOTDB_READ_DATA_0008"  # 向后获取时间戳
    API_URL_TIME_RANGE = "http://eplat.baogang.info/service/D_A_IOTDB_READ_DATA_0001"  # 按时间范围获取数据（信号/模拟量）
    API_URL_TIME_NEWEST = "http://eplat.baogang.info/service/D_A_IOTDB_READ_DATA_0003"  # 取最新的值
    CLIENT_ID = "iedas-line18d5120ykI6o374Xr"
    CLIENT_SECRET = "0A9883E2EC88652C44F403823BADD205"

    # 获取信号数据时，先获取信号的开始时间和结束时间(19位时间戳)，注意path末尾要加".I"
    @staticmethod
    def get_signal_info(path, now_time, flag=1):
        if flag == 1:
            url = GetIotData.API_URL_TIME_BEFORE
        else:
            url = GetIotData.API_URL_TIME_AFTER

        params = {
            "clientId": GetIotData.CLIENT_ID,
            "clientSecret": GetIotData.CLIENT_SECRET,
            "params": {
                "path": path + ".I",
                "queryTime": now_time
            },
            "showCount": "false",
            "isEnableLimit": "false"
        }

        response = requests.post(url, json=params)

        if response.status_code == 200:
            api_data = response.json()
            # print(len(api_data['__blocks__']))
            if len(api_data['__blocks__']) == 0:
                return False, []
            else:
                result_row = api_data['__blocks__']['result']['rows']
                # print(type(result_row))
                if len(result_row) == 0:
                    return False, []
                else:
                    result_I = result_row[0]  # 列表，按顺序分别是：开始时间戳、Hz、结束时间戳、cl
                return True, result_I
        else:
            # print(f'Error: {response.status_code} - {response.text}')
            return False, []

    # 获取时间范围内的数据(包括信号数据+单值数据，区别在于信号数据path末尾要加".S" 以及 tag="Value")
    @staticmethod
    def get_value_time_range(path, tag, start_time, end_time, if_signal=False):
        if if_signal:
            path_new = path + ".S"
        else:
            path_new = path
        params = {
            "clientId": GetIotData.CLIENT_ID,
            "clientSecret": GetIotData.CLIENT_SECRET,
            "params": {
                "path": path_new,
                "tag": tag,
                "start_time": start_time,
                "end_time": end_time
            },
            "showCount": "false",
            "isEnableLimit": "false"
        }

        response = requests.post(GetIotData.API_URL_TIME_RANGE, json=params)

        if response.status_code == 200:
            api_data = response.json()
            result_S = api_data['__blocks__']['result']['rows']  # 列表，按顺序分别是：开始时间戳、Hz、结束时间戳、cl
            return True, result_S
        else:
            # print(f'Error: {response.status_code} - {response.text}')
            return False, []

    # 获取信号数据，返回run_status, msg, rst，分别为运行状态，报错信息，结果(dict格式，包括 hz cl value_list)
    @staticmethod
    def get_iot_signal(path, now_time, flag):
        if_res1, info_list1 = GetIotData.get_signal_info(path, now_time, flag)
        run_status = False
        msg = ""
        rst = {}
        if if_res1:
            if_res2, info_list2 = GetIotData.get_value_time_range(path, "Value", info_list1[0], info_list1[2], True)
            if if_res2:
                run_status = True
                values = list(map(lambda x: float(x[1]), info_list2))
                rst = {
                    'hz': int(info_list1[1]),
                    'cl': int(info_list1[3]),
                    'values': values,
                    'start_time': info_list1[0],
                    'end_time': info_list1[2]
                }
            else:
                msg = "信号数据查询api调用失败！"
        else:
            msg = "时间范围查询api调用失败！"
        return run_status, msg, rst

    @staticmethod
    def get_iot_value(path, tag, start_time, end_time):
        run_status = False
        msg = ""
        rst = {}
        if_res, info_list = GetIotData.get_value_time_range(path, tag, start_time, end_time, False)
        if if_res:
            run_status = True
            rst = pd.DataFrame(info_list)
            rst.columns = ['datetime', 'value']
        else:
            msg = "信号数据查询api调用失败！"
        return run_status, msg, rst


if __name__ == '__main__':
    log_time1 = time.time()
    path = "root.BGTA.BGTAIOAA00.IDL4_MF_GWS_01.clN"
    now_time = "2023/12/06 14:42:41.560"
    flag = 1
    run_status, msg, rst = GetIotData.get_iot_signal(path, now_time,flag)
    path = "root.BGTA.BGTAIOAD00.AD_DMM_01.PLC"
    tag = "2050_FMC_COMFU_MRG_F6_MOT1_ArmatureTemp_Act"  # 2050_FMC_COMFU_MRG_F6_MOT2_ArmatureTemp_Act
    end_time = (int(time.time()) - 5 * 60) * 10 ** 9
    start_time = (int(time.time()) - 15 * 60) * 10 ** 9
    # start_time = "1696694400000000000"
    # end_time = "1701964800000000000"
    run_status, msg, rst = GetIotData.get_iot_value(path, tag, start_time, end_time)
    # print(len(rst))
    rst.to_excel(tag+".xlsx")
    log_time2 = time.time()
    # print(f"用时：{log_time2-log_time1}s")
